#include "filehandler.h"


FileHandler::FileHandler(const QString &file, QObject* obj): filepath(file), object(obj)
{

}

void FileHandler::loadFile(const QString &filename)
{
    process = new QProcess(this);
    QString file("./SaveDE&ENcry/SaveToolDe.exe");
    process->start(file, QStringList(filename));
    connect(process, &QProcess::finished, this, [this,filename](){
        namespace fs = std::filesystem;
        qDebug() << filename << Qt::endl;
        fs::path filepath(filename.toStdString());
        fs::path generatedfile = filepath.replace_filename(fs::path("DataUnit.json"));
        if(!fs::exists(generatedfile)){
            qDebug() << "don't Exists!" << Qt::endl;
            emit json_generated(false);
        }else{
            json_file = QString::fromStdString(generatedfile.generic_string());
            emit json_generated(true);
            qDebug() << "Exists!" << Qt::endl;
        }
        process->disconnect(this);
//        process->disconnect(this);
    });
}

QMap<QString, QString> FileHandler::loadJson()
{
    qDebug() << "Json File: " << json_file << Qt::endl;
    if(!json_file.isEmpty()){
        file = new QFile(json_file);
        file->open(QIODevice::ReadOnly | QIODevice::Text);
        QString value = file->readAll();
        QJsonParseError parserJsonErr;
        document = QJsonDocument::fromJson(value.toUtf8(), &parserJsonErr);
        if(!(parserJsonErr.error == QJsonParseError::NoError)){
            qDebug() << tr("解析json文件错误");
            return {};
        }
        file->flush();
        file->close();
        QRegularExpression re(":{.+?\"");
        auto match = re.match(value);
    //    QRegularExpressionMatch match;
        auto firstmatch = match.captured(0);
        re.setPattern("[A-Za-z0-9]+");
        nameid = re.match(firstmatch).captured(0);
        qDebug() << "Name ID = " << nameid << Qt::endl;
        QJsonObject jsonObject = document.object();
        auto character = jsonObject["allUnit"].toObject()[nameid].toObject()["q"].toObject();
    //    qDebug() << "Hello There" << jsonObject["allUnit"].toObject().keys()[0] << Qt::endl;
        auto name = character["q"]; //Array
        auto attack = character["1"]; //int
        auto defense = character["2"]; //int
        auto footSpeed = character["3"]; //int
        auto crit = character["7"]; //int
        auto guard = character["9"]; //int
        auto critValue = character["8"]; //int
        auto guardValue = character["qq"]; //int
        auto reputation = character["a"]; //int
        auto mpMax = character["b"]; //int
        auto mp = character["v"]; //int
        auto hpMax = character["c"]; //int
        auto hp = character["x"]; //int
        auto spMax = character["m"]; //int
        auto sp = character["n"]; //int
        auto talent = character["k"]; //int
        auto moveSpeed = character["qw"]; //int
        auto sex = character["r"]; //int 2 for male 1 for female
        auto race = character["t"];
        auto physicalFree = character["qe"]; //int
        auto magicFree = character["qr"]; //int
        auto fire = character["qt"]; //int
        auto froze = character["qy"]; //int
        auto thunder = character["qu"]; //int
        auto wind = character["qi"]; //int
        auto earth = character["qo"]; //int
        auto wood = character["qp"]; //int
        auto sword = character["qa"];
        auto spear = character["qs"];
        auto blade = character["qd"];
        auto fist = character["qf"];
        auto palm = character["qg"];
        auto finger = character["qh"];
        auto refineElixir = character["qj"];
        auto refineWeapon = character["qk"];
        auto geomancy = character["ql"];
        auto symbol = character["qz"];
        auto herbal = character["wq"];
        auto mine = character["ww"];
        auto mood = character["qx"];
        auto moodMax = character["qc"];
        auto abilityPoint = character["j"];
        auto life = character["u"];
        auto luck = character["4"];
        auto beauty = character["i"];
        auto healthMax = character["z"];
        auto energyMax = character["6"];

        qDebug() << "Here" << Qt::endl;
        QMap<QString, QString> map{
            {"lastname", name.toArray()[0].toString()},
            {"firstname", name.toArray()[1].toString()},
            {"abilityPoint", QString::number(abilityPoint.toInt())},
            {"moodMax", QString::number(moodMax.toInt())},
            {"mood", QString::number(mood.toInt())},
            {"mine", QString::number(mine.toInt())},
            {"herbal", QString::number(herbal.toInt())},
            {"symbol", QString::number(symbol.toInt())},
            {"geomancy", QString::number(geomancy.toInt())},
            {"refineWeapon", QString::number(refineWeapon.toInt())},
            {"refineElixir", QString::number(refineElixir.toInt())},
            {"finger", QString::number(finger.toInt())},
            {"palm", QString::number(palm.toInt())},
            {"fist", QString::number(fist.toInt())},
            {"blade", QString::number(blade.toInt())},
            {"spear", QString::number(spear.toInt())},
            {"sword", QString::number(sword.toInt())},
            {"wood", QString::number(wood.toInt())},
            {"earth", QString::number(earth.toInt())},
            {"wind", QString::number(wind.toInt())},
            {"thunder", QString::number(thunder.toInt())},
            {"froze", QString::number(froze.toInt())},
            {"fire", QString::number(fire.toInt())},
            {"magicFree", QString::number(magicFree.toInt())},
            {"physicalFree", QString::number(physicalFree.toInt())},
            {"race", QString::number(race.toInt())},
            {"sex", QString::number(sex.toInt())},
            {"moveSpeed", QString::number(moveSpeed.toInt())},
            {"talent", QString::number(talent.toInt())},
            {"spMax", QString::number(spMax.toInt())},
            {"mpMax", QString::number(mpMax.toInt())},
            {"hpMax", QString::number(hpMax.toInt())},
            {"reputation", QString::number(reputation.toInt())},
            {"guardValue", QString::number(guardValue.toInt())},
            {"guard", QString::number(guard.toInt())},
            {"critValue", QString::number(critValue.toInt())},
            {"crit", QString::number(crit.toInt())},
            {"footSpeed", QString::number(footSpeed.toInt())},
            {"defense", QString::number(defense.toInt())},
            {"attack", QString::number(attack.toInt())},
            {"life", QString::number(life.toInt()/12)},
            {"luck", QString::number(luck.toInt())},
            {"beauty", QString::number(beauty.toInt())},
            {"healthMax", QString::number(healthMax.toInt())},
            {"energyMax", QString::number(energyMax.toInt())}
        };
        return map;
    }else{
        return {};
    }


}

void FileHandler::saveFile(const QMap<QString, QString>& map)
{
    QJsonObject jsonObject = document.object();
    auto character = jsonObject["allUnit"].toObject()[nameid].toObject()["q"].toObject();
//    character.insert("q", QJsonArray({map["lastname"], map["firstname"]}));
    character["q"] = QJsonArray({map["lastname"], map["firstname"]});
    character["1"] = map["attack"].toInt();
    character["2"] = map["defense"].toInt(); //int
    character["3"] = map["footSpeed"].toInt(); //int
//    character["7"] = map["crit"].toInt(); //int
    character["9"] = map["guard"].toInt(); //int
    character["8"] = map["critValue"].toInt(); //int
    character["qq"] = map["guardValue"].toInt(); //int
    character["a"] = map["reputation"].toInt(); //int
    character["b"] = map["mpMax"].toInt(); //int
//    auto mp = character["v"]; //int
    character["c"] = map["hpMax"].toInt(); //int
//    auto hp = character["x"]; //int
    character["m"] = map["spMax"].toInt(); //int
//    auto sp = character["n"]; //int
    character["k"] = map["talent"].toInt(); //int
    character["qw"] = map["moveSpeed"].toInt(); //int
    character["r"] = map["sex"].toInt(); //int 2 for male 1 for female
    character["t"] = map["race"].toInt();
    character["qe"] = map["physicalFree"].toInt(); //int
    character["qr"] = map["magicFree"].toInt(); //int
    character["qt"] = map["fire"].toInt(); //int
    character["qy"] = map["froze"].toInt(); //int
    character["qu"] = map["thunder"].toInt(); //int
    character["qi"] = map["wind"].toInt(); //int
    character["qo"] = map["earth"].toInt(); //int
    character["qp"] = map["wood"].toInt(); //int
    character["qa"] = map["sword"].toInt();
    character["qs"] = map["spear"].toInt();
    character["qd"] = map["blade"].toInt();
    character["qf"] = map["fist"].toInt();
    character["qg"] = map["palm"].toInt();
    character["qh"] = map["finger"].toInt();
    character["qj"] = map["refineElixir"].toInt();
    character["qk"] = map["refineWeapon"].toInt();
    character["ql"] = map["geomancy"].toInt();
    character["qz"] = map["symbol"].toInt();
    character["wq"] = map["herbal"].toInt();
    character["ww"] = map["mine"].toInt();
//    character["qx"] = map["mood"].toInt();
    character["qc"] = map["moodMax"].toInt();
    character["j"] = map["abilityPoint"].toInt();
    character["u"] = map["life"].toInt()*12;
    character["4"] = map["luck"].toInt();
    character["i"] = map["beauty"].toInt();
    character["z"] = map["healthMax"].toInt();
    character["6"] = map["energyMax"].toInt();
    QJsonObject jo;
    jo.insert("q", character);
    QJsonObject jo2 = jsonObject["allUnit"].toObject();
    jo2.insert(nameid, jo);
    jsonObject.insert("allUnit", jo2);
//    jsonObject["allUnit"].toObject()[nameid].toObject()["q"] = character;
    document.setObject(jsonObject);
    qDebug() << character["q"] << Qt::endl;
    file->open(QIODevice::WriteOnly | QIODevice::Text);
    file->seek(0);
    auto byte_array = document.toJson(QJsonDocument::Compact);
    QString json_str(byte_array);
    QTextStream in(file);
    in << json_str;
//    file->write(document.toJson(QJsonDocument::Compact));
    file->flush();
    file->close();

    QString file("./SaveDE&ENcry/SaveToolEn.exe");
    process->start(file, QStringList({json_file}));
    connect(process, &QProcess::finished, this, [this](){
        namespace fs = std::filesystem;
        fs::path filepath(json_file.toStdString());
//        fs::remove(filepath);
        qDebug() << "Save Done" << Qt::endl;
        process->disconnect(this);
    });

}
